# 导入web3模块，用于与以太坊交互
import web3
# 导入uniswap模块，用于与uniswap交易
import uniswap

# 设置我的账号地址和私钥，这里只是示例，你应该用自己的账号和私钥
my_address = '0x123456789abcdef0123456789abcdef012345678'
my_private_key = '0xabcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789'
version = 2 # or 3 for Uniswap V3
provider = "https://mainnet.infura.io/v3/f3fde5c8dc7a42d99214014edbebb793" # or your own node

# 卖代币，接受两个参数：合约地址和代币数量
def swap_token(contract_address, token_amount):
    # 创建一个web3对象，连接到本地节点
    w3 = web3.Web3(web3.Web3.HTTPProvider('http://localhost:8545'))
    # 创建一个uniswap对象，传入我的账号地址和私钥
    uni = uniswap.Uniswap(my_address, my_private_key)
    # 获取合约地址对应的代币对象
    token = uni.get_token(contract_address)
    # 获取代币的符号和精度
    token_symbol = token.symbol()
    token_decimals = token.decimals()
    # 转换代币数量为最小单位，根据代币的精度
    token_amount_in_min_unit = int(token_amount * (10 ** token_decimals))
    # 调用uniswap的交换函数，将代币换成以太坊，返回交易哈希
    tx_hash = uni.swap_token_for_eth(token, token_amount_in_min_unit)
    # 打印交易哈希和交易详情
    print(f'Transaction hash: {tx_hash.hex()}')
    print(f'Swapped {token_amount} {token_symbol} for ETH at market price')

# 买代币，接受两个参数：合约地址和代币数量
def swap_eth(contract_address, eth_amount):
    # 创建一个web3对象，连接到本地节点
    w3 = web3.Web3(web3.Web3.HTTPProvider('http://localhost:8545'))
    # 创建一个uniswap对象，传入我的账号地址和私钥
    uni = uniswap.Uniswap(my_address, my_private_key)
    # 获取合约地址对应的代币对象
    token = uni.get_token(contract_address)
    # 获取代币的符号和精度
    token_symbol = token.symbol()
    token_decimals = token.decimals()
    # 转换以太坊数量为wei单位，1 ether = 10**18 wei
    eth_amount_in_wei = w3.toWei(eth_amount, 'ether')
    # 调用uniswap的交换函数，将以太坊换成代币，返回交易哈希
    tx_hash = uni.swap_eth_for_token(token, eth_amount_in_wei)
    # 打印交易哈希和交易详情
    print(f'Transaction hash: {tx_hash.hex()}')
    print(f'Swapped {eth_amount} ETH for {token_symbol} at market price')


def swap_dai(contract_address,num):
    uniswap1 = uniswap.Uniswap(my_address, my_private_key, provider=provider, version=version)
    token = uniswap1.get_token(contract_address)
    print(token.symbol)
    print(token.decimals)
    print(token.name)
    eth = uniswap1.get_token("0x0000000000000000000000000000000000000000")
    dai = uniswap1.get_token(contract_address)#想要得到的代币
    tx_hash = uniswap1.swap(eth, dai, num) # swap 1 ETH for DAI
    print(tx_hash)